<template>
  <view class="make-template-container">
    <view class="header-container">
      <u-search
        shape="square"
        placeholder="搜搜你想要的产品吧~"
        v-model="searchForm.title"
        bg-color="#fff"
        :action-style="{
          'color': '#56d39d'
        }"
        @search="handleSearch"
        @custom="handleSearch"
        @clear="handleSearch"></u-search>
      
      <!-- 标题 -->
      <view class="nav-category-container">
        <view
          v-for="(item, index) in navList"
          :key="item.picType"
          class="nav-category-item"
          :class="{
            'active': currentPicType === index
          }"
          @click="handlePicType(index)">
          {{ item.label }}
        </view>
      </view>

      <view v-if="navList && navList[currentPicType] && navList[currentPicType].cateList && navList[currentPicType].cateList.length > 1" class="cate-container">
        <u-tabs
          name="short_title"
          class="cate_count"
          inactive-color="#172B4D"
          :list="navList[currentPicType].cateList"
          :is-scroll="true"
          :current="currentTab"
          bg-color="#f8f8f8"
          active-color="#56d39d"
          gutter="16"
          height="40"
          font-size="24"
          :duration="0"
          :show-bar="false"
          :active-item-style="{
            'background': 'rgb(224, 238, 252)',
            'border-radius': '20rpx',
            'height': '40rpx',
            'line-height': '36rpx',
          }"
          @change="selectTab"></u-tabs>
      </view>
    </view>

    <!-- 视频列表 -->
    <template v-if="templateList.length > 0">
      <view class="peitu-list">
        <DiyAvatarList
          :artworks-list="templateList"
          @handleArtworks="handleArtworks"
          @handleCheckBox="handleCheckBox"></DiyAvatarList>
      </view>
    </template>
    <!-- 没有数据 -->
    <template v-else>
      <view v-if="showNoMoreFlag" class="u-flex u-flex-col u-col-center" style="width: 100vw;height: 78vh;padding-top: 200rpx;">
        <view class="">
          <image
            style="width: 300rpx;height: 300rpx;"
            src="https://img.alicdn.com/imgextra/i1/1888948409/O1CN01CSQqUP2BzNNzcB96v_!!1888948409.png">
          </image>
        </view>
        <view class="u-tips-color u-font-12 u-p-t-30">
          没有数据哦~
        </view>
      </view>
    </template>

    <view v-if="scrollTop > 200" class="is_top" @click="handleTop"></view>

    <!-- 操作栏 -->
    <view class="bottom-main">
      <view class="bottom-view">
        <view class="bottom-view-button bottom-view-button-before" @click="confirmAddTemplate">
          <u-icon name="checkbox-mark" color="#56d39d" size="28"></u-icon>
          <text class="bottom-view-button-text">确定添加</text>
        </view>
        <view @click="goBack()" class="bottom-view-button bottom-view-button-padding bottom-view-button-margin0">
          <text class="huiju-iconfont huiju-icon-fanhui1"></text>
          <text class="bottom-view-button-text">返回上一页</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import DiyAvatarList from '@/components/artworksList/diyAvatarList.vue';
  import {
    makeTemplateCategoryList,
    makeTemplateAllListByToolId
  } from '@/api/applet.js';
  import {
    makeTemplateAddArtworksLabel,
    addMakePublicTemplate
  } from '@/api/artworks';
  export default {
    components: {
      DiyAvatarList
    },
    data() {
      return {
        showNoMoreFlag: false,
        keyword: '',
        navList: [],
        currentPicType: 0,
        currentTab: 0,
        searchForm: {
          pageNum: 1,
          pageSize: 40,
          tool_id: -1,
          tool_ids: [],
          searchType: 'wallpaper',
          title: '',
          get_type: 'client',
          author_id: '',
          type: '',
          get_list: true
        },
        templateList: [],
        scrollTop: 0,
        author_id: '',
        type: '',
        artworksListObject: {}
      }
    },
    
    onLoad(options) {
      this.author_id = options.author_id;
      this.searchForm.author_id = options.author_id;
      this.searchForm.type = options.type;
      this.type = options.type;
      this.getplayCategoryListByToolType();
    },

    methods: {

      // 确定添加
      async confirmAddTemplate() {
        uni.showLoading({
          title: '加载中',
          mask: true
        });
        let selectTemplateList = this.templateList.filter(item => item.checked);
        let cate_id = this.navList[this.currentPicType].cate_id;
        let label_name = this.navList[this.currentPicType] && this.navList[this.currentPicType].cateList[this.currentTab] ? this.navList[this.currentPicType].cateList[this.currentTab].short_title : '';
        if (selectTemplateList && selectTemplateList.length > 0) {
          let label_id = '';
          if (label_name) {
            label_id = await this.getMakeTemplateArtworksLabel({
              cate_id,
              label_name,
              author_id: this.author_id,
            });
          }
          let templateList = selectTemplateList.map(item => {
            return {
              template_id: item.id,
              tool_id: item.tool_id,
              cover_url: item.thumbnail,
              wx_cover_url: item.cover_url,
              title: item.title,
              cate_id,
              type: this.type,
              author_id: this.author_id,
              label_id
            }
          });
          addMakePublicTemplate({
            templateList
          }).then(result => {
            uni.hideLoading();
            if (result && result.code === 200) {
              uni.showToast({
                title: '添加成功！',
                icon: 'none',
              })
              setTimeout(() => {
                let pages = getCurrentPages();
                let pagesLength = pages.length;
                if (pagesLength > 1) {
                  uni.navigateBack({
                    delta: 1,
                  })
                } else {
                  let pages = getCurrentPages();
                  let pagesLength = pages.length;
                  if (pagesLength > 1) {
                    uni.navigateBack({
                      delta: 1,
                    })
                  } else {
                    let pages = getCurrentPages();
                    let pagesLength = pages.length;

                    if (pagesLength > 1) {
                      uni.navigateBack({
                        delta: 1,
                      })
                    } else {
                      uni.switchTab({ url: '/pages/creativeCenter/index' });
                    }
                  }
                }
              }, 1000);
            }
          });
        } else {
          uni.hideLoading();
          uni.showToast({
            title: '请选择！',
            icon: 'none'
          })
        }
      },

      // 查找标签
      async getMakeTemplateArtworksLabel(data) {
        return new Promise((resolve, reject) => {
          makeTemplateAddArtworksLabel(data).then(result => {
            if (result && result.data) {
              resolve(result.data.id);
            } else {
              reject('');
            }
          })
        })
      },

      // 返回
      goBack() {
        let pages = getCurrentPages();
        let pagesLength = pages.length;

        if (pagesLength > 1) {
          uni.navigateBack({
            delta: 1,
          })
        } else {
          uni.switchTab({ url: '/pages/creativeCenter/index' });
        }
      },

      // 点击搜索
      handleSearch() {
        this.templateList = [];
        this.showNoMoreFlag = false;
        this.searchForm.pageNum = 1;
        this.getTemplateAllListByToolId();
      },

      // 点击作品
      handleCheckBox(id) {
        let index = this.templateList.findIndex(item => item.id === id);
        this.templateList[index].checked = !this.templateList[index].checked;
      },
      
      // 置顶
      handleTop() {
        uni.pageScrollTo({
          scrollTop: 0
        })
      },

      // 点击小分类
      selectTab(index) {
        this.currentTab = index;
        this.searchForm.title = '';
        this.templateList = [];
        this.searchForm.tool_ids = [];
        this.searchForm.pageNum = 1;
        this.showNoMoreFlag = false;
        this.getTemplateAllListByToolId();
      },

      // 点击大分类
      handlePicType(index) {
        this.searchForm.pageNum = 1;
        this.currentPicType = index;
        this.currentTab = 0;
        this.templateList = [];
        this.showNoMoreFlag = false;
        this.searchForm.tool_id = '';
        this.searchForm.tool_ids = [];
        let pic_type = this.navList[index].picType;
        this.searchForm.searchType = pic_type;
        this.getTemplateAllListByToolId();
      },

      // 获取列表
      getTemplateAllListByToolId() {
        let that = this;
        uni.showLoading({
          title: '加载中...'
        });
        this.searchForm.tool_id = this.navList[this.currentPicType] && this.navList[this.currentPicType].cateList[this.currentTab] ? this.navList[this.currentPicType].cateList[this.currentTab].id : '';
        makeTemplateAllListByToolId(that.searchForm).then(result => {
          uni.hideLoading();
          if (result && result.data && result.data.records && result.data.records.length > 0) {
            this.searchForm.get_list = false;

            // 已添加的作品
            let artworksListObject = this.artworksListObject;
            if (result.data.artworksList && result.data.artworksList.length > 0) {
              let artworksList = result.data.artworksList;
              artworksList.forEach(item => {
                artworksListObject[item.template_id] = item;
              });
              this.artworksListObject = artworksListObject;
            }

            let listData = result.data.records;
            listData.forEach(item => {
              item.type = this.navList[this.currentPicType].cate_id;
              item.checked = false;
              if (artworksListObject[item.id]) {
                item.select = true;
              } else {
                item.select = false;
              }
            });
            console.log(listData)
            that.templateList = [...that.templateList, ...listData];
            if (that.searchForm.pageNum === result.data.total_pages) {
              that.showNoMoreFlag = true;
              that.loadStatus = 'nomore';
            } else {
              that.loadStatus == 'loadmore';
            }
            that.searchForm.pageNum = that.searchForm.pageNum + 1;
          } else {
            that.templateList = [];
            that.loadStatus = 'nomore';
            that.showNoMoreFlag = true;
          }
        }).catch(() => {
          uni.hideLoading();
        });
      },

      // 获取分类
      getplayCategoryListByToolType() {
        let that = this;
        makeTemplateCategoryList({
          tool_type: 8,
        }).then(result => {
          let navList = result.data.navList;
          let list = result.data.list;
          that.navList = navList;
          that.cateList = list;
          this.getTemplateAllListByToolId();
        });
      }
    },
    //下拉
    onReachBottom() {
      let that = this;
      if (!this.showNoMoreFlag) {
        this.getTemplateAllListByToolId();
      } else {
        uni.showToast({
          title: '没有更多的数据啦！',
          icon: 'none'
        })
      }
    },
    onPageScroll(res){
      this.scrollTop = res.scrollTop;
    }
  }
</script>

<style lang="scss">

  page{
    background-color: #fff;
  }

  .make-template-container{

    .header-container{
      top: 0;
      position: sticky;
      z-index: 1000;
      background-color: #f8f8f8;
      padding: 24rpx;
      border-radius: 0 0 16rpx 16rpx;
    }

    .nav-category-container{
      display: flex;
      padding: 24rpx 12rpx;
      justify-content: space-between;

      .nav-category-item{
        padding: 0;
        font-size: 32rpx;
        position: relative;
        padding: 6rpx 12rpx;
        color: #888;
        font-weight: bold;
      }

      .nav-category-item.active{
        color: $uni-color-primary;
      }

      .nav-category-item.active::before{
        display: block;
        content: '';
        width: 20rpx;
        height: 4rpx;
        border-radius: 2rpx;
        background-color: $uni-color-primary;
        position: absolute;
        left: 0;
        right: 0;
        bottom: -10rpx;
        margin: auto;
      }
    }

    .cate-container{
      padding-top: 12rpx;
    }

    .peitu-list{
      padding: 24rpx;
    }
  }

  .is_top{
    width: 88rpx;
    height: 88rpx;
    position: fixed;
    right: 10rpx;
    bottom: 200rpx;
    border-radius: 50%;
    z-index: 999;
    background: rgba($color: #000000, $alpha: .4) url(https://img.alicdn.com/imgextra/i4/1888948409/O1CN010UtwPo2BzNOb9hVkv_!!1888948409.png) no-repeat center / 60%;
  }

  .bottom-main{
    position: fixed;
    bottom: calc(var(--window-bottom) + 60rpx);
    z-index: 20;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    z-index: 999;

    .bottom-view{
      display: flex;
      justify-content: center;
      min-width: 400rpx;
      padding: 24rpx 30rpx;
      background: #fff;
      border: 2rpx solid $uni-color-primary2;
      border-radius: 92rpx;

      &-button{
        color: $uni-color-primary;
        font-size: 24rpx;
        position: relative;
        padding-right: 34rpx;
        margin-right: 34rpx;
        white-space: nowrap;

        &-text{
          color: $uni-color-primary;
          padding-left: 6rpx;
        }
      }

      &-button-before{
        &::before{
          content: "";
          position: absolute;
          right: 0;
          width: 2rpx;
          height: 32rpx;
          background: #e9e9e9;
        }
      }

      &-button-padding{
        padding-right: 16rpx;
        margin-right: 16rpx;
      }

      &-button-margin0{
        margin-right: 0;
        padding-right: 0;
      }
    }
  }
</style>
